import os
from datetime import datetime

import django.db.utils
import qiniu
from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_POST

from apps.aiauth.models import Users
from apps.message.serializers import Comments, CommentsSerializers
from apps.message.serializers import ResumeSerializers, Message
from apps.resume.models import Resume
from apps.setup.models import Experts
from utils import restful


def qntoken(request):
    access_key = 'MV_lAU8gYHytJGVOUFvHEM6EgLs2lxHZjT-fHT3a'
    secret_key = 'AzCg1IylthqfHSevzsst5e_5STc5an6cKLrK8DPQ'
    q = qiniu.Auth(access_key, secret_key)
    bucket = 'careerai'
    token = q.upload_token(bucket)

    return restful.result(code=200, kwargs={"token": token})


def addResume(request):
    file_url = request.POST.get('file_url')
    file_name = request.POST.get('file_name')
    expert = Experts.objects.get(experts_id=request.POST.get('experts_id'))

    user_id = request.POST.get('user_Id')
    user = Users.objects.get(user_id=user_id)
    try:
        resume = Resume.objects.create(
            experts=expert,
            user_id=user,
            file_url=file_url,
            create_time=datetime.now(),
            status=1,
            can_del=1,
            is_dot=1,
            file_name=file_name
        )
        return restful.result(data={'resume_id': resume.resume_id}, message="成功")

    except django.db.utils.IntegrityError:
        return restful.params_error(message="该文件已存在！请勿重复上传")


def deleteResume(request):
    resume_id = request.GET.get('resume_id')
    resume = Resume.objects.get(resume_id=resume_id, can_del=1)
    resume.delete()

    return restful.ok(message="删除成功")


def ResumeList(request):
    pagenow = request.GET.get('pagenow', 1)
    size = request.GET.get('pagesize', 10)
    user_id = request.GET.get('user_id')
    organization_id = request.GET.get('organization')
    realName = request.GET.get('studentName')
    student_id = request.GET.get('studentId')
    search_dict = {}
    if user_id:
        search_dict['user_id'] = user_id
    if organization_id:
        search_dict['user_id__userinfo__organization_id'] = organization_id
    if realName:
        search_dict['user_id__realname__iexact'] = realName
    if student_id:
        search_dict['user_id__studentid'] = student_id
    resumeList = Resume.objects.filter(
        **search_dict,
    ).order_by('-create_time')
    obj = Paginator(resumeList, size)
    obj_data = obj.get_page(pagenow)
    totalcount = obj.count
    data = ResumeSerializers(obj_data.object_list, many=True).data

    return JsonResponse({
        "message": '成功',
        "code": 200,
        "data": {
            "data": data,
            "totalcount": totalcount
        }
    })


def addMessage(request):
    to_id = request.POST.get('toId')
    from_field = Users.objects.get(user_id=request.POST.get('fromId'))
    type = request.POST.get('type')
    content = request.POST.get('content')
    jumpurl = request.POST.get('jumpurl')
    Message.objects.create(
        to_id=to_id,
        from_field=from_field,
        type=type,
        content=content,
        jumpurl=jumpurl,
        isread=0,
        create_time=datetime.now()
    )
    return restful.ok(message="成功")


# type = 0是简历评论
# status 1为正常，0为删除，2仅老师可见，默认1
def ResumeCommentList(request):
    search_dict = {
        'type': '0'
    }
    user_id = request.GET.get('user_id')
    experts_id = request.GET.get('experts_id')
    pagenow = request.GET.get('pagenow', 1)
    is_author = request.GET.get('is_author')  # 1是作者，0是专家
    if user_id:
        search_dict['user_id'] = user_id
    if is_author:
        search_dict['is_author'] = is_author
    if experts_id:
        search_dict['experts_id'] = experts_id
    comments = Comments.objects.filter(
        **search_dict
    ).filter(~Q(status=0)).order_by('-create_time')
    page_obj = Paginator(comments, 10)
    page_data = page_obj.get_page(pagenow)
    totalcount = page_obj.count
    data = CommentsSerializers(page_data.object_list, many=True).data

    return JsonResponse({
        "message": '成功',
        "code": 200,
        "data": {
            "data": data,
            "totalcount": totalcount
        }
    })


# 删除评论，将状态改为0
def deleteComment(request):
    comments_id = request.GET.get('comments_id')
    comment = Comments.objects.get(comments_id=comments_id)
    comment.status = 0
    comment.save()

    return restful.ok(message="删除成功！")


@require_POST
def upload_file(request):
    file = request.FILES.get('file')
    name = file.name
    with open(os.path.join(settings.MEDIA_ROOT, name), 'wb') as fp:
        for chunk in file.chunks():
            fp.write(chunk)
    url = request.build_absolute_uri(settings.MEDIA_URL + name)

    return restful.result(data={'url': url})

